/**
 * @param {Number} 毫秒数
 * @param {Function} 倒计时结束回调
 * @param {Boolean} 是否暂停倒计时
 * @description 创建倒计时实例
 */
 export class BuildCountdown {
  constructor (ms, timeEndCallback, pause = false) {
    this.ms = ms
    this.timeEndCallback = timeEndCallback
    this.setTimer(ms, pause)
  }

  timer = null
  remainSecond = 0

  get inCountdown () {
    return !!this.timer
  }

  get hour () {
    return this.filterString(Math.floor(this.remainSecond / 3600))
  }

  get minute () {
    return this.filterString(Math.floor(this.remainSecond / 60 % 60))
  }

  get seconds () {
    return this.filterString(Math.floor(this.remainSecond % 60))
  }

  get outPutString () {
    return `${this.hour}时${this.minute}分${this.seconds}秒`
  }

  // 创建定时器
  setTimer (ms, pause) {
    if (!ms || ms < 0) return
    this.remainSecond = ms / 1000
    if (pause) return
    this.timer = setInterval(() => {
      if (this.remainSecond <= 0) {
        this.handleTimeEnd()
        return
      }
      this.remainSecond--
    }, 1000)
  }

  // 刷新定时器
  refreshTimer () {
    this.removeTimer()
    this.setTimer(this.ms)
  }

  handleTimeEnd () {
    this.removeTimer()
    this.timeEndCallback && this.timeEndCallback()
  }

  removeTimer () {
    clearInterval(this.timer)
    this.timer = null
  }

  filterString (value) {
    if (value < 0) return 0
    else return value >= 10 ? value : `0${value}`
  }
}